<template>
    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible="open" width="50%" append-to-body @close="closeDialog">
        <DialogTit slot="title" :title="title"></DialogTit>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-row>
                <el-col :span="24">
                    <el-form-item :label="'上级岗位'" prop="pid" size="small">
                        <treeselect :disabled="deptOptions.length?false:true" v-model="form.pid" :options="deptOptions" :normalizer="normalizer" @input="pidChange" :placeholder="$t('public.select_holder',{select_holder: $t('deptManage.superiorDept')})" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item :label="$t('postManage.postName')" prop="postName" size="small">
                        <el-input v-model="form.postName" :placeholder="$t('public.placeholder',{placeholder:$t('deptManage.deptName')})" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item :label="$t('deptManage.showSort')" prop="sort" size="small">
                        <el-input-number v-model="form.sort" controls-position="right" :min="0" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item :label="$t('deptManage.chargePerson')" prop="userName" size="small">
                        <el-tooltip effect="dark" :disabled="form.userName?false:true" :content="form.userName" placement="top">
                            <select-user-dialog multiple v-model="form.userName" :placeholder="$t('public.placeholder',{placeholder:$t('deptManage.chargePerson')})" :titleName="$t('ncr.selectPerson')" @sendData="sendCallback" />
                        </el-tooltip>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item :label="$t('public.contactPhone')" prop="userTelephone" size="small">
                        <el-tooltip effect="dark" :disabled="form.userTelephone?false:true" :content="form.userTelephone" placement="top">
                            <el-input v-model="form.userTelephone" disabled :placeholder="$t('public.placeholder',{placeholder:$t('public.contactPhone')})" />
                        </el-tooltip>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item :label="$t('public.email')" prop="userEmail" size="small">
                        <el-tooltip effect="dark" :disabled="form.userEmail?false:true" :content="form.userEmail" placement="top">
                            <el-input v-model="form.userEmail" disabled :placeholder="$t('public.placeholder',{placeholder:$t('public.email')})" />
                        </el-tooltip>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item prop="state" :label="$t('postManage.postStatus')" size="small">
                        <el-radio-group v-model="form.state">
                            <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{dict.label}}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item :label="$t('defectIncoming.materialMiddle')" prop="materialMiddleName">
                        <materialMiddleDialog multiple v-model="form.materialMiddleName" :titleName="$t('ncr.selectMastrialMiddle')" @callback="callback" :placeholder="$t('public.selectPl')+$t('defectIncoming.materialMiddle')" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="cancel" size="small" icon="el-icon-close">{{$t('public.cancel')}}</el-button>
            <el-button type="primary" @click="submitForm" size="small" icon="el-icon-check">{{$t('public.define')}}</el-button>
        </div>
    </el-dialog>
</template>

<script>
import { getMasterialMaxMinData } from '@/api/basic/materialtype'
import SelectUserDialog from '@/views/components/SelectUserDialog'
import materialMiddleDialog from '@/views/components/materialMiddleDialog'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { addRank, getAllRank, getPostUser, editRank } from '@/api/system/rank'
export default {
    name: 'rankDialog',
    dicts: ['sys_normal_disable'],
    props: ['title', 'open', 'isType', 'rowData', 'parentId'],
    components: {
        Treeselect,
        SelectUserDialog,
        materialMiddleDialog,
    },
    data() {
        return {
            // 部门树选项
            deptOptions: [],
            form: {
                pid: null,
                id: '',
                postName: null,
                sort: null,
                userTelephone: null,
                userId: null,
                userEmail: null,
                state: '0',
                materialMiddleName: null,
                materialMediumId: [],
                listPost: [],
                listUser: [],
            },
            // 表单校验
            rules: {
                pid: [
                    {
                        required: true,
                        trigger: 'change',
                        validator: (rule, value, callback) => {
                            if (!this.deptOptions.length) {
                                callback()
                            } else {
                                if (!value) {
                                    return callback(new Error('请选择上级岗位'))
                                }
                                callback()
                            }
                        },
                    },
                ],
                postName: [
                    {
                        required: true,
                        message: '请输入岗位名称',
                        trigger: 'blur',
                    },
                ],
                sort: [
                    {
                        required: true,
                        message: '请输入排序',
                        trigger: 'blur',
                    },
                ],
                materialMiddleName: [
                    {
                        required: true,
                        message: '请选择物料中类',
                        trigger: 'change',
                    },
                ],
            },
            // 查询参数
            queryParams: {
                postName: '',
                status: '',
            },
            checkMans: [],
            materialMiddleOptions: [],
        }
    },
    watch: {
        rowData: {
            handler(newVal) {
                if (newVal) {
                    let obj = JSON.parse(JSON.stringify(newVal))
                    this.getListUser(obj.id, obj)
                }
            },
            deep: true,
            immediate: true,
        },
        parentId: {
            handler(newVal) {
                if (newVal) {
                    this.form.pid = newVal
                }
            },
            deep: true,
            immediate: true,
        },
    },
    created() {
        this.getRanks()
        this.getMaterialType({ materialMax: 'all' }, 'materialMiddle')
    },
    methods: {
        pidChange(value) {
            if (value) this.$refs.form.validateField('pid')
        },
        getListUser(id, obj) {
            getPostUser({ postId: id }).then((res) => {
                if (res.rows && res.rows.length) {
                    obj['userName'] = res.rows.map((i) => i.userName).join(',')
                    obj['userId'] = res.rows.map((i) => i.userId).join(',')
                    obj['userEmail'] = res.rows
                        .map((i) => i.userEmail)
                        .join(',')
                    obj['userTelephone'] = res.rows
                        .map((i) => i.userTelephone)
                        .join(',')
                }
                this.form = obj
            })
        },
        /** 转换部门数据结构 */
        normalizer(node) {
            if (node.listPost && !node.listPost.length) {
                delete node.listPost
            }
            return {
                id: node.id || '0',
                label: node.postName,
                children: node.listPost,
            }
        },
        getRanks() {
            getAllRank(this.queryParams).then((response) => {
                this.deptOptions = response.data
            })
        },
        getMaterialType(params, key) {
            let array = []
            getMasterialMaxMinData(params).then((res) => {
                array = res.data.map((item) => item[key])
                this.materialMiddleOptions = array
            })
        },
        cancel() {
            this.$emit('update:open', false)
        },
        sendCallback(array) {
            this.checkMans = array
            let tel = array.map((item) => item.phonenumber || '')
            let email = array.map((item) => item.email || '')
            let userId = array.map((item) => item.userId || '')
            this.form.userTelephone = tel.join(',')
            this.form.userEmail = email.join(',')
            this.form.userId = userId.join(',')
        },
        submitForm() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    const params = JSON.parse(JSON.stringify(this.form))
                    delete params.userName
                    delete params.userTelephone
                    delete params.userEmail
                    delete params.userId
                    if (this.isType == 1) {
                        if (this.deptOptions.length) {
                            params.id = ''
                        } else {
                            params.pid = '0'
                        }
                    }
                    if (this.checkMans.length) {
                        params.listUser = []
                        this.checkMans.forEach((el) => {
                            params.listUser.push({
                                userName: el.userName,
                                userTelephone: el.phonenumber,
                                userEmail: el.email,
                                userId: el.userId,
                            })
                        })
                    }
                    let action = this.isType === 1 ? addRank : editRank
                    action(params).then((res) => {
                        if (res.code === 200) {
                            this.$modal.msgSuccess(res.msg)
                            this.$emit('update:open', false)
                            this.$emit('refresh')
                        }
                    })
                }
            })
        },
        closeDialog() {
            this.resetForm('form')
            this.$emit('update:open', false)
        },
        callback(arr) {
            if (arr.length) this.$refs.form.validateField('materialMiddleName')
        },
    },
}
</script>

<style>
</style>